package com.zhxl.mvc.Dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.zhxl.model.Internal.User;
public class QueryContextDaoImpl2{
	/*
	 * 	java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
	 */
	SessionFactory sessionFactory;
	public Session getSession(){
		return sessionFactory.openSession();
	}
	public List<User> getContext() {
		List<User> users = new ArrayList<User>();
		
		System.out.println(getSession()==null);
		Session session = getSession();
		/**
		 * 使用Session session = getSessionFactory().getCurrentSession();报错Could not obtain transaction-synchronized
		 */
		//could not open connect access denied for user 
		//username or password 错误
		
		Transaction transaction = session.beginTransaction();
		/*
		 * 下面写法报错nested transactions not supportedat org.
		 * 事务嵌套异常
		 */
		//session.beginTransaction().begin();
		//session.beginTransaction().begin();
		User u = null;
		u = (User) session.get(User.class, "12");
		/**
		 * from user其中user一定要与model的entity name值一致
		 */
		users = session.createQuery("from user").list();
		if(users.size()>0){
			return users;
		}
		String name = u.getName();
		System.out.println(name);
		transaction.commit();
		if(u == null){
			u = new User();
			u.setAge("1024");
			u.setName("QQQ");
		}
		users.add(u);
		return users;
	}
}
